﻿$(function () {
    var cloudImportList = $("cloud-import");
    for (var i = 0; i < cloudImportList.length; i++) {
        var cloudImport = cloudImportList[i];
        var cloudImportBtnID = "cloudImportBtnID" + $(cloudImport).attr("id");
        var cloudImportFileID = "cloudImportFileID_" + $(cloudImport).attr("id");
        var btntext = $(cloudImport).attr("btntext");
        var url = $(cloudImport).attr("url");
        var afterimport = $(cloudImport).attr("afterimport");
        var handleurl = "";
        if (url.substr(0, 7) == "http://" || url.substr(0, 1) == "/" || url.substr(0, 11) == "javascript:") {
            handleurl = url;
        } else {
            handleurl = GetRootPath() + url;
        }
        var text = "";
        text += " <button class=\"btn btn-op btn-import\" type=\"button\" id='" + cloudImportBtnID + "'><span class=\"btntext\">" + btntext + "</span></button>";
        text += "<input type=\"file\" id='" + cloudImportFileID + "' style=\"display:none\"  />";
        cloudImport.innerHTML = text;
        $("#" + cloudImportBtnID).click(function () {
            $("#" + cloudImportFileID).click();
        })
        $("#" + cloudImportFileID).change(function () {
            if (handleurl != "") {
                var fileUpload = $("#" + cloudImportFileID).get(0);
                var files = fileUpload.files;
                var formData = new FormData();
                for (var i = 0; i < files.length; i++) {
                    formData.append(files[i].name, files[i]);
                }
                CloudPostFile(formData, handleurl, function (res) {
                    if (res.code == 0) {
                        if (afterimport) {
                            eval(afterimport);
                        }
                    } else {
                        OpenFail(res.data);
                    }
                })
                $("#" + cloudImportFileID).val('');
            }
        })
    }
})